import type {
  GetProp,
  TableColumnsType,
  TableProps,
  TransferProps,
} from 'antd';
import { Table, Transfer } from 'antd';
import React from 'react';
import CommonTable from '../CommonTable';

type TransferItem = GetProp<TransferProps, 'dataSource'>[number];
type TableRowSelection<T extends object> = TableProps<T>['rowSelection'];

interface TableTransferProps extends TransferProps<TransferItem> {
  value?: any[];
  dataSource: any[];
  leftColumns: TableColumnsType<any>;
  rightColumns: TableColumnsType<any>;
}

const TableTransfer: React.FC<TableTransferProps> = (props) => {
  const { leftColumns, rightColumns, rowKey, value, ...restProps } = props;
  return (
    <Transfer style={{ width: '100%' }} targetKeys={value} {...restProps}>
      {({
        direction,
        filteredItems,
        onItemSelect,
        onItemSelectAll,
        selectedKeys: listSelectedKeys,
        disabled: listDisabled,
      }) => {
        const columns = direction === 'left' ? leftColumns : rightColumns;
        const rowSelection: TableRowSelection<TransferItem> = {
          getCheckboxProps: () => ({ disabled: listDisabled }),
          onChange(selectedRowKeys) {
            onItemSelectAll(selectedRowKeys, 'replace');
          },
          selectedRowKeys: listSelectedKeys,
          selections: [
            Table.SELECTION_ALL,
            Table.SELECTION_INVERT,
            Table.SELECTION_NONE,
          ],
        };

        return (
          <CommonTable
            rowKey={rowKey}
            rowSelection={rowSelection}
            columns={columns}
            dataSource={filteredItems}
            style={{ pointerEvents: listDisabled ? 'none' : undefined }}
            onRow={({ key, disabled: itemDisabled }) => ({
              onClick: () => {
                if (itemDisabled || listDisabled) {
                  return;
                }
                onItemSelect(key, !listSelectedKeys.includes(key));
              },
            })}
            pagination={{
              showSizeChanger: false,
              showQuickJumper: false,
            }}
            // pagination={false}
            // scroll={{ y: 500 }}
          />
        );
      }}
    </Transfer>
  );
};

export default TableTransfer;
